import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wanandroid/common/api.dart';
import 'package:flutter_wanandroid/entity/project_entity.dart';
import 'package:flutter_wanandroid/httpUtils/http_util.dart';
import 'package:flutter_wanandroid/pages/flutter_webview.dart';
import 'package:flutter_wanandroid/res/colors.dart';

import '../entity/project_list_entity.dart';

class ProjectPage extends StatefulWidget {
  const ProjectPage({Key? key}) : super(key: key);

  @override
  State<ProjectPage> createState() => _ProjectPageState();
}

class _ProjectPageState extends State<ProjectPage>
    with TickerProviderStateMixin {
  TabController? _tabController;
  late EasyRefreshController _easyRefreshController;
  List<ProjectData> _datas = [];
  int currentIndex = 0; //选中的下标
  int _page = 1; //看文档时要注意page是从0还是1开始
  List<ProjectListDataData> _listDatas = []; //内容集合
  bool hasMore = true;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 0, vsync: this);
    _easyRefreshController = EasyRefreshController(
        controlFinishRefresh: true, controlFinishLoad: true);
    getHttp();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TabBar(
        //控制器
        controller: _tabController,
        //选中的颜色
        labelColor: Theme.of(context).primaryColor,
        //选中的样式
        labelStyle: const TextStyle(fontSize: 16),
        //未选中的颜色
        unselectedLabelColor: YColors.color_666,
        //未选中的样式
        unselectedLabelStyle: const TextStyle(fontSize: 14),
        //下划线颜色
        indicatorColor: Theme.of(context).primaryColor,
        //是否可滑动
        isScrollable: true,
        //tab标签
        tabs: _datas.map((e) {
          return Padding(
            padding: EdgeInsets.symmetric(vertical: 10),
            child: Text(
              e.name ?? "",
              style: TextStyle(
                fontSize: 16,
              ),
            ),
          );
        }).toList(),
        onTap: (int index) {
          print("切换tab:$index");
        },
      ),
      body: TabBarView(
        controller: _tabController,
        children: _datas.map((ProjectData choice) {
          return EasyRefresh(
            controller: _easyRefreshController,
            header: TaurusHeader(),
            footer: TaurusFooter(),
            onRefresh: () async {
              await Future.delayed(Duration(seconds: 1), () {
                setState(() {
                  _page = 1;
                });
                getHttp();
              });
            },
            onLoad: () async {
              await Future.delayed(Duration(seconds: 1), () {
                setState(() {
                  _page++;
                });
                getMoreData();
                _easyRefreshController.finishLoad(
                    hasMore ? IndicatorResult.success : IndicatorResult.noMore);
              });
            },
            child: CustomScrollView(
              slivers: [
                SliverList(
                  delegate: SliverChildBuilderDelegate((context, index) {
                    return getRow(index);
                  }, childCount: _listDatas.length),
                ),
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  Widget getRow(int i) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.all(10.0),
        child: Card(
          elevation: 5,
          color: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(10),
            ),
          ),
          child: Padding(
            padding: EdgeInsets.all(10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  flex: 2,
                  child: Image.network(_listDatas[i].envelopePic ?? ""),
                ),
                Expanded(
                    flex: 5,
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: Text(
                            _listDatas[i].title ?? "",
                            style: TextStyle(
                                fontSize: 16, fontWeight: FontWeight.bold),
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(
                              horizontal: 10, vertical: 10),
                          child: Text(
                            _listDatas[i].desc ?? "",
                            style: TextStyle(
                                fontSize: 14, color: YColors.color_666),
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Expanded(
                                flex: 2,
                                child: Text(_listDatas[i].niceDate ?? ""),
                              ),
                              Expanded(
                                flex: 1,
                                child: Text(_listDatas[i].author ?? ""),
                              )
                            ],
                          ),
                        )
                      ],
                    ))
              ],
            ),
          ),
        ),
      ),
      onTap: () {
        //点击item跳转到详情
        print(i);
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => FlutterWebView(
                title: _listDatas[i].title, uri: _listDatas[i].link),
          ),
        );
      },
    );
  }

  void getHttp() async {
    var response = await HttpUtil().get(Api.PROJECT);
    var userMap = json.decode(response.toString());
    ProjectEntity projectEntity =
        ProjectEntity.fromJson(userMap) as ProjectEntity;
    if (mounted) {
      setState(() {
        if (projectEntity != null && projectEntity.data != null) {
          _datas = projectEntity.data!;
          _tabController = TabController(length: _datas.length, vsync: this);
        }
      });
      getDetail();
      //tab增加监听
      _tabController?.addListener(() => _onTabChanged());
    }
  }

  //tab改变监听
  void _onTabChanged() {
    if (_tabController?.index.toDouble() == _tabController?.animation?.value) {
      setState(() {
        currentIndex = _tabController?.index ?? 0;
      });
      getDetail();
    }
  }

  ///
  /// 根据tab下标获取数据
  ///
  void getDetail() async {
    try {
      var data = {"cid": _datas[currentIndex].id};
      var response =
          await HttpUtil().get(Api.PROJECT_LIST + "$_page/json", data: data);
      Map<String, dynamic> userMap = json.decode(response.toString());
      var projectListEntity =
          ProjectListEntity.fromJson(userMap) as ProjectListEntity;

      setState(() {
        if (projectListEntity.data != null &&
            projectListEntity.data!.datas != null) {
          _listDatas = projectListEntity.data!.datas!;
        }
      });
    } catch (e) {
      print(e);
    }
  }

  void getMoreData() async {
    try {
      var data = {"cid": _datas[currentIndex].id};
      var response =
          await HttpUtil().get(Api.PROJECT_LIST + "$_page/json", data: data);
      Map<String, dynamic> map = json.decode(response.toString());
      var projectListEntity =
          ProjectListEntity.fromJson(map) as ProjectListEntity;
      if (mounted) {
        setState(() {
          if (projectListEntity != null &&
              projectListEntity.data != null &&
              projectListEntity.data!.datas != null) {
            List<ProjectListDataData> projectDatas =
                projectListEntity.data!.datas!;
            _listDatas.addAll(projectDatas);
            if (projectDatas.isNotEmpty || projectDatas.length < 20) {
              hasMore = false;
            }
          } else {
            hasMore = false;
          }
        });
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  void dispose() {
    _tabController?.dispose();
    _easyRefreshController.dispose();
    super.dispose();
  }
}
